<template>
  <div class="main-content">
    <div class="view-title">
      <!--      <h2>版本管理</h2>-->
    </div>
    <div class="table-bar">
      <tool-bar
        :cond.sync="filterBy"
        @create="handleCreate"
        @refresh="refresh"
        @search="handleSearch"
      />
    </div>
    <div class="table-content">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="tableData"
        border
        class="table"
        max-height="700"
        header-cell-class-name="table-header"
        tooltip-effect="light"
        :default-sort="defaultSortConf"
        @sort-change="changeSort"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" width="50" align="center" label="序号" />
        <template v-for="item in tableColumn">
          <el-table-column
            v-if="item.type !== 'popover'"
            :key="item.index"
            :prop="item.index"
            :width="item.width"
            :label="item.label"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :show-overflow-tooltip="item.tip"
          />
          <el-table-column
            v-else
            :key="item.index"
            :prop="item.index"
            :width="item.width"
            :label="item.label"
            :formatter="item.formatter"
            :show-overflow-tooltip="item.tip"
          >
            <template slot-scope="scope">
              <el-popover trigger="click" placement="top">
                <el-table border :data="parseDescription(scope.row.description)" max-height="300px">
                  <el-table-column width="150" property="lang" label="语言类型" />
                  <el-table-column
                    width="300"
                    property="description"
                    label="描述信息"
                    :show-overflow-tooltip="true"
                  />
                </el-table>
                <el-tag slot="reference" size="medium" class="name-wrapper" style="cursor:pointer">
                  点击查看
                </el-tag>
              </el-popover>
            </template>
          </el-table-column>
        </template>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-footer">
      <el-pagination
        :current-page="pageInfo.pageNum"
        :page-sizes="pageInfo.sizeItems"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.totalSize"
        :page-count="pageInfo.totalPages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <version-create-dialog
      :type="dialogType"
      :servers="servers"
      :visible.sync="dialogVisible"
      @callback="loadData"
    />
  </div>
</template>
<script>
import fota from '../../api/fota'
import { formatTimeToStr } from '../../utils/index'
import ToolBar from './toolBar'
import VersionCreateDialog from './createDialog'

export default {
  components: { ToolBar, VersionCreateDialog },
  data() {
    return {
      loading: false,
      tableColumn: [],
      tableData: [],
      servers: [],
      pageInfo: {},
      delList: [],
      dialogVisible: false,
      dialogType: 'create',
      sortConf: {},
      defaultSortConf: { prop: 'releaseTime', order: 'descending' },
      filterBy: {}
    }
  },
  computed: {
    uploadDisabled: {
      get: function() {
        return this.dialog.data.server === undefined ||
          this.dialog.data.product === undefined ||
          this.dialog.data.product.trim() === ''
      }
    }
  },
  created() {
    this.initTableBaseInfo()
  },
  mounted() {
    this.loadData()
  },
  methods: {
    handleSearch() {
      this.loadData()
    },
    refresh() {
      this.filterBy = { timeRange: [] }
      this.loadData()
    },
    handleCreate() {
      this.dialogType = 'create'
      this.dialogVisible = true
    },
    handleDelete(index, row) {
      this.$refs.multipleTable.clearSelection()
      this.delList.push(row)
      this.delAllSelection()
    },
    delAllSelection() {
      const tmp = this.delList.concat(this.multipleSelection || [])
      if (tmp.length === 0) {
        return
      }
      this.$confirm('此操作将永久删除版本是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = ''
        this.delList = tmp
        for (let i = 0; i < this.delList.length; i++) {
          param += this.delList[i].id
          if (i !== this.delList.length - 1) {
            param += ','
          }
        }
        this.loading = true
        this.deleteModel(param)
        this.delList = []
      }).catch(err => {
        console.log(`未知异常: ${JSON.stringify(err)}`)
      })
    },
    deleteModel: function(param) {
      this.loading = true
      const self = this
      fota.deletePkg(param).then(() => {
        fota.notifySuccess('版本删除成功。')
        self.initPkgList()
      }, () => {
        fota.notifyError(`版本删除失败！`)
        self.loading = false
      })
    },
    initTableBaseInfo() {
      this.tableColumn = [
        { index: 'product', label: '产品', tip: true, sortable: 'custom' },
        { index: 'version', label: '版本', tip: true, sortable: 'custom' },
        { index: 'uri', label: '所在服务器', formatter: this.serverFormatter },
        { index: 'sizeText', label: '文件大小', width: 110, formatter: this.sizeFormatter, sortable: 'custom' },
        { index: 'releaseTime', label: '发布时间', width: 160, formatter: this.timeFormatter, sortable: 'custom' },
        { index: 'description', label: '描述', tip: true, width: 100, type: 'popover' },
        { index: 'flag', label: '标识', width: 100, tip: true, formatter: this.flagFormatter },
        { index: 'remark', label: '备注', tip: true }
      ]
      this.pageInfo = {
        pageNum: 1,
        pageSize: 10,
        totalPages: 1,
        totalSize: 1,
        sizeItems: [10, 20, 50, 100, 200, 500, 1000]
      }
      this.sortConf = this.defaultSortConf
    },
    handleSizeChange: function(newSize) {
      this.pageInfo.pageSize = newSize
      this.loading = true
      this.initPkgList()
    },
    handleCurrentChange: function(pageNum) {
      this.pageInfo.pageNum = pageNum
      this.loading = true
      this.initPkgList()
    },
    getOrderByCond() {
      const columnMapping = { sizeText: 'size', releaseTime: 'release_time' }
      const orderMapper = { descending: 'desc', ascending: 'asc' }
      return `${(columnMapping[this.sortConf.prop] || this.sortConf.prop)} ${orderMapper[this.sortConf.order]}`
    },
    initPkgList: function() {
      const self = this
      const param = { pageNum: this.pageInfo.pageNum, pageSize: this.pageInfo.pageSize, orderBy: this.getOrderByCond(), filterBy: this.filterBy }
      fota.queryPkgList(param).then(res => {
        self.tableData = res.data.data
        self.pageInfo.totalPages = res.data.totalPages
        self.pageInfo.totalSize = res.data.totalSize
        self.loading = false
      }, () => {
        fota.notifyError(`查询版本信息失败！`)
        self.loading = false
      })
    },
    initFotaServers: function() {
      const self = this
      fota.queryFotaServers().then(res => {
        self.servers = res.data.servers
        self.loading = false
      }, () => {
        fota.notifyError(`服务器信息查询失败！`)
        self.loading = false
      })
    },
    changeSort: function({ prop, order }) {
      if (order === null) {
        this.sortConf = this.defaultSortConf
      } else {
        this.sortConf = { prop: prop, order: order }
      }
      this.loadData()
    },
    loadData() {
      this.loading = true
      this.initPkgList()
      this.initFotaServers()
    },
    serverFormatter: function(row) {
      const uri = row.uri
      const ip = uri.match(/https?:\/\/([^\/:]*):?.*\/.*/)[1]
      const item = this.servers.filter(item => {
        const address = item.domain
        return address && address.match(/([^:]*):?.*/)[1] === ip
      })
      return item === null || item.length === 0 ? `${ip} [undefined]` : item[0].name
    },
    timeFormatter: function(row) {
      return formatTimeToStr(row.releaseTime)
    },
    flagFormatter: function(row) {
      const flagStr = row.flag
      if (flagStr === undefined || flagStr === null) {
        return '-'
      }
      const flag = JSON.parse(flagStr)
      const rst = Object.entries(flag).map(item => {
        return `${item[0]}:${item[1]}`
      })
      return rst.join(';')
    },
    sizeFormatter: function(row) {
      if (row.sizeText !== '') {
        return row.sizeText
      } else if (row.size !== 0) {
        return `${((row.size / (1024 * 1024)).toFixed(2))}MB`
      } else {
        return '0MB'
      }
    },
    parseDescription(item) {
      const descList = []
      try {
        const descObj = JSON.parse(item)
        for (const lang in descObj) {
          descList.push({ lang: lang, description: descObj[lang] })
        }
      } catch (e) {
        descList.push({ lang: 'default', description: item })
      }
      return descList
    }
  }
}
</script>

<style scoped>
  .main-content {
    padding: 16px;
  }

  .table-bar {
    margin: 0 8px 8px 0;
  }

  .table-footer {
    float: right;
    margin-top: 8px;
  }
</style>
